package com.itluma.myproject.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

/**
 * @author 飞鸟
 * @create 2021-05-18 10:33
 */
public class JsonUtils {

    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将对象转换成json格式字符串
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 将字符串转换成对象
     * @param json
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T parseObject(String json, Class<T> cls) {
        try {
            return objectMapper.readValue(json, cls);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将字符串转换成集合类型
     * @param json
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> List<T> parseList(String json, Class<T> cls) {
        try {
            return objectMapper.readValue(json, new TypeReference<List<T>>(){});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
